/**
 * H5环境请求封装
 */
export const h5Request = (options) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    const method = options.method.toUpperCase();
    
    // 处理GET请求参数
    if (method === 'GET' && options.params) {
      let url = options.url;
      const queryString = Object.keys(options.params)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(options.params[key]))
        .join('&');
        
      if (url.indexOf('?') === -1) {
        url += '?' + queryString;
      } else {
        url += '&' + queryString;
      }
      
      options.url = url;
    }
    
    // 打开请求
    xhr.open(method, options.url, true);
    
    // 设置超时
    xhr.timeout = options.timeout || 30000;
    
    // 设置请求头
    if (options.header) {
      Object.keys(options.header).forEach(key => {
        xhr.setRequestHeader(key, options.header[key]);
      });
    }
    
    // 监听请求状态
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        let response;
        try {
          response = JSON.parse(xhr.responseText);
        } catch (e) {
          response = xhr.responseText;
        }
        
        resolve({
          data: response,
          status: xhr.status,
          statusText: xhr.statusText,
          headers: xhr.getAllResponseHeaders()
        });
      } else {
        reject({
          response: {
            data: xhr.responseText,
            status: xhr.status,
            statusText: xhr.statusText
          },
          message: `请求失败: ${xhr.status}`
        });
      }
    };
    
    // 处理请求错误
    xhr.onerror = function() {
      reject({
        message: '网络请求错误'
      });
    };
    
    // 处理超时
    xhr.ontimeout = function() {
      reject({
        message: '请求超时'
      });
    };
    
    // 发送请求
    if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
      let data = options.data;
      
      // 如果是对象且Content-Type为application/json，则转换为JSON字符串
      if (typeof data === 'object' && options.header && options.header['Content-Type'].includes('application/json')) {
        data = JSON.stringify(data);
      }
      
      xhr.send(data);
    } else {
      xhr.send();
    }
  });
}; 